package souralven.jcomicreader.controller.reader.impl;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

import souralven.jcomicreader.controller.reader.FileReader;
import souralven.jcomicreader.util.ImageUtil;

public class ZipFileReader implements FileReader {

	@Override
	public InputStream read(File file, int imageNumber) {
		try {
			final ZipFile zipFile = new ZipFile(file);
			final Enumeration<? extends ZipEntry> entries = zipFile.entries();
			int count = 0;
			// TODO handle dirs
			List<ZipEntry> list = new ArrayList<ZipEntry>();
			while (entries.hasMoreElements()) {
			    list.add(entries.nextElement());
			}
			Collections.sort(list, new Comparator<ZipEntry>() {
                @Override
                public int compare(ZipEntry e1, ZipEntry e2) {
                    return e1.getName().compareTo(e2.getName());
                }
            });
			for (ZipEntry zipEntry : list) {
			    if (ImageUtil.hasImageFormat(zipEntry.getName())) {
			        if (count == imageNumber) {
			            return zipFile.getInputStream(zipEntry);
			        }
			        count++;
			    }
			}
		} catch (ZipException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public int count(File file) {
		try {
			return new ZipFile(file).size();
		} catch (ZipException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return 0;
	}
}
